//
//  ZZOrderPopView.m
//  新项目
//
//  Created by liGordon on 17/3/6.
//  Copyright © 2017年 刘耀宗. All rights reserved.
//

#import "ZZOrderPopView.h"
#import "ZZScrollBtn.h"
@interface ZZOrderPopView ()<UITextFieldDelegate>

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *allButtons;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *channelView;
@property (nonatomic, strong) NSMutableArray *channels;
@property (nonatomic, copy) void(^myblock)() ;
/**
 *  记录当前显示的频道新闻Cell的item
 */
@property (nonatomic, assign) NSInteger currentIndex;
@property (weak, nonatomic) IBOutlet UITextField *chePaiField;
@property (weak, nonatomic) IBOutlet UITextField *startTimeField;
@property (weak, nonatomic) IBOutlet UITextField *endTimeField;



@property (nonatomic,strong) UIDatePicker *datePicker;
@property (nonatomic,strong) UIDatePicker *datePicker1;
@property(nonatomic,strong) UIToolbar *toolBar;
@property (nonatomic, assign) NSInteger tagNum;

@property(nonatomic,strong) UIToolbar *toolBar1;
@property (nonatomic, strong) NSDictionary *dic;

@end

@implementation ZZOrderPopView
- (NSMutableArray *)channels {
    if (_channels == nil) {
        _channels = [NSMutableArray array];
    }
    return _channels;
}


-(void)awakeFromNib
{
    [super awakeFromNib];
    [self.allButtons enumerateObjectsUsingBlock:^(UIButton *otherButton, NSUInteger idx, BOOL *stop) {
        [otherButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [otherButton.layer setMasksToBounds:YES];
        [otherButton.layer setCornerRadius:8.0];
    }];
    [self.searchBtn.layer setMasksToBounds:YES];
    [self.searchBtn.layer setCornerRadius:20.0];
    
    self.startTimeField.delegate=self;
    self.endTimeField.delegate=self;
    NSDate *date=[NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    formatter.dateFormat=@"yyyy-MM-dd";
    NSString *STR=[formatter stringFromDate:date];
    self.endTimeField.text=STR;
    
    NSTimeInterval time=24*60*60*31;
    NSDate *date1=[date dateByAddingTimeInterval:-time];
    NSString *STR2=[formatter stringFromDate:date1];
    self.startTimeField.text=STR2;
  
}
//查询
- (IBAction)clickForSeletecd:(id)sender {
    if ([self.delegate respondsToSelector:@selector(seletecdDataWithplatNum:andStartTime:andEndTime:andDic:)]) {
        if (self.chePaiField.text.length==0||self.chePaiField.text==nil) {
            self.chePaiField.text=@"";
        }
        [self.delegate seletecdDataWithplatNum:self.chePaiField.text andStartTime:self.startTimeField.text andEndTime:self.endTimeField.text andDic:self.dic];
    }

}
-(void)setTypeArr:(NSArray *)typeArr
{
    _typeArr=typeArr;
    if (typeArr.count!=0) {
        //移除所有的
        [self.channels removeAllObjects];
        self.dic=typeArr[0];
        
        for (NSDictionary *dic in typeArr) {
            [self.channels addObject:[NSString stringWithFormat:@"%@",dic[@"Name"]]];
        }
        
        [self setupChannel];
    }
    
}

-(void)clickForCHooseType
{
    self.myblock();

}

// 在 iOS 7.0 之后，如果视图控制器中有 UINavigationController + UIScrollView的组合，会默认调整 UIScrollView 的边距，从而达到穿透 Nav 的效果
/**
 *  添加频道标签
 */
- (void)setupChannel {
    // 设置不要自动调整UIScrollView的内边距
//    self.channelView.automaticallyAdjustsScrollViewInsets = NO;
    
    // 获得channelView的高度
    CGFloat channelH = self.channelView.frame.size.height;
    // 频道标签之间的间隙
    CGFloat marginX = 8;
  __block  CGFloat lableX = marginX;
    [self.channels enumerateObjectsUsingBlock:^(NSString *  _Nonnull name, NSUInteger idx, BOOL * _Nonnull stop) {
        // 创建 频道标签
        ZZScrollBtn *btn = [ZZScrollBtn btnWithTitle:name];
        // 设置x和y值
        btn.frame = CGRectMake(lableX, 0, btn.frame.size.width, channelH);
        
        // 设置tag标签
        btn.tag =idx;
        
        __weak typeof(self) weakVc = self;
        __weak typeof(btn) weakChannelLabel = btn;
        [btn setSelectedlabel:^{
            //            // 获得频道标签中心点的x值
            CGFloat centerX = weakChannelLabel.center.x;
            // 计算屏幕宽度的一半
            CGFloat halfOfScreen = [UIScreen mainScreen].bounds.size.width * 0.5;
            // 获得scrollView最大滚动范围
            CGFloat maxOffsetX = weakVc.channelView.contentSize.width - [UIScreen mainScreen].bounds.size.width ;
            // 计算偏移量
            CGFloat offsetX = centerX - halfOfScreen;
            if (offsetX < 0) {
                offsetX = 0;
            } else if (offsetX > maxOffsetX) {
                offsetX = maxOffsetX;
            }
            [weakVc.channelView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
            [self.channelView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[UIButton class]]) {
                    [obj setBackgroundColor:CXBColor(202   , 202, 202)];
                    [obj setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }
                
            }];
            
            
            [weakChannelLabel setBackgroundColor:CXBColor(20, 107, 170)];
            [weakChannelLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.dic=self.typeArr[idx];
//            if ([self.delegate respondsToSelector:@selector(reFreashwithType:)]) {
//                [self.delegate reFreashwithType:self.typeArr[idx]];
//            }
        }];
        
        // 将频道标签添加channelView上
        [self.channelView addSubview:btn];
        lableX += btn.frame.size.width+20;
        
    }];
    // 设置滚动范围
    self.channelView.contentSize = CGSizeMake(lableX + marginX, 0);
    self.channelView.showsHorizontalScrollIndicator = NO;
}

- (IBAction)topButtonPressed:(UIButton *)sender
{
    [self.allButtons enumerateObjectsUsingBlock:^(UIButton *otherButton, NSUInteger idx, BOOL *stop) {
        [otherButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [otherButton setBackgroundColor:CcColor(235, 235, 235)];
        [otherButton.layer setMasksToBounds:YES];
        [otherButton.layer setCornerRadius:8.0];
    }];
   

    
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sender setBackgroundColor:CcColor(6, 127, 183)];
    [sender.layer setMasksToBounds:YES];
    [sender.layer setCornerRadius:8.0];
    if ([sender.currentTitle isEqualToString:@"全部"]) {
        
    } else if ([sender.currentTitle isEqualToString:@"维修"]) {
        
    } else if ([sender.currentTitle isEqualToString:@"保养"]) {
        
    } else if ([sender.currentTitle isEqualToString:@"美容"]) {
        
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}

#pragma mark - 监听按钮的点击事件
- (void)complete{
    
    [self endEditing:YES];
    //隐藏
    //[self compareStartTimeAndEndTime];
    
    
    
}
//比较当前的开始时间和结束时间
-(BOOL)compareStartTimeAndEndTime
{
    NSString *startTime=self.startTimeField.text;
    NSArray *startArr=[startTime componentsSeparatedByString:@"-"];
    //年份
    NSInteger startNian=[startArr[0] integerValue];
    NSInteger startYue=[startArr[1] integerValue];
    NSInteger startRi=[startArr[2] integerValue];
    NSString *endTime=self.endTimeField.text;
    NSArray *endArr=[endTime componentsSeparatedByString:@"-"];
    //年份
    NSInteger endNian=[endArr[0] integerValue];
    NSInteger endYue=[endArr[1] integerValue];
    NSInteger endRi=[endArr[2] integerValue];
    
    if (startNian>endNian) {
        [self showError];
    }else
    {
        if (startYue>endYue) {
            [self showError];
            
        }else
        {
            if (startRi>endRi) {
                [self showError];
                
            }else
            {
                //                if ([self.delegate respondsToSelector:@selector(chooseTimeWithStartTime:andEndTime:)]) {
                //                    [self.delegate chooseTimeWithStartTime:self.startTimeField.text andEndTime:self.endTimeField.text];
                //                }
                
            }
            
        }
        
        
        
        
    }
    
    
    
    
    
    return YES;
    
    
    
}
-(void)showError
{
    NSDate *date=[NSDate date];
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    formatter.dateFormat=@"yyyy-MM-dd";
    NSString *STR=[formatter stringFromDate:date];
    self.endTimeField.text=STR;
    
    NSTimeInterval time=24*60*60*31;
    NSDate *date1=[date dateByAddingTimeInterval:-time];
    NSString *STR2=[formatter stringFromDate:date1];
    self.startTimeField.text=STR2;
    
    [MBProgressHUD showError:@"时间区间选择错误"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 隐藏登录指示器
        [MBProgressHUD hideHUD];
    });
    
}
#pragma mark -  开始编辑
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField.placeholder isEqualToString:@"开始时间不能大于结束时间"]) {
        self.tagNum=200;
        
    }else if ([textField.placeholder isEqualToString:@"结束时间不能低于开始时间"])
    {
        self.tagNum=201;
        
    }
    
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{

    if ([textField.placeholder isEqualToString:@"开始时间不能大于结束时间"]) {
        textField.inputAccessoryView=self.toolBar;
        textField.inputView=self.datePicker;
        
    }else if ([textField.placeholder isEqualToString:@"结束时间不能低于开始时间"])
    {
        textField.inputAccessoryView=self.toolBar1;
        textField.inputView=self.datePicker1;
    }
    return YES;
}


- (UIToolbar *)toolBar {
    if (_toolBar == nil) {
        // 1.创建键盘工具条
        UIToolbar *toolbar = [[UIToolbar alloc] init];
        toolbar.frame = CGRectMake(0, 0, 320, 44);
        toolbar.barTintColor = blueColor;
        toolbar.tintColor = [UIColor whiteColor];
        UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        // 4. 完成
        UIBarButtonItem *complete = [[UIBarButtonItem alloc] initWithTitle:@"确定" style: UIBarButtonItemStyleDone target:self action:@selector( complete)];
        UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:@"选择结束时间" style: UIBarButtonItemStyleDone target:self action:@selector(chooseEndTime)];
        toolbar.items = @[flexibleSpace,next,complete];
        _toolBar = toolbar;
    }
    return _toolBar;
}
-(void)chooseEndTime
{
    [self.endTimeField becomeFirstResponder];
}
- (UIToolbar *)toolBar1 {
    if (_toolBar1 == nil) {
        // 1.创建键盘工具条
        UIToolbar *toolbar = [[UIToolbar alloc] init];
        toolbar.frame = CGRectMake(0, 0, 320, 44);
        toolbar.barTintColor = blueColor;
        toolbar.tintColor = [UIColor whiteColor];
        UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        // 4. 完成
        UIBarButtonItem *complete = [[UIBarButtonItem alloc] initWithTitle:@"确定" style: UIBarButtonItemStyleDone target:self action:@selector( complete)];
        UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:@"选择开始时间" style: UIBarButtonItemStyleDone target:self action:@selector( chooseStartTime)];
        toolbar.items = @[flexibleSpace,next,complete];
        _toolBar1 = toolbar;
    }
    return _toolBar1;
}
-(void)chooseStartTime
{
    [self.startTimeField becomeFirstResponder];
}
#pragma mark - 懒加载控件
- (UIDatePicker *)datePicker {
    
    DLog(@"创建了日期选择器");
    // 创建日期选择器
    // 一般不需要设置宽高
    _datePicker = [[UIDatePicker alloc] init];
    // 设置时区
    _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    // 设置时间模式
    _datePicker.datePickerMode = UIDatePickerModeDate;
    // 设置最小选择时间
    //        _datePicker.minimumDate =[NSDate date];
    //[NSDate dateWithTimeIntervalSinceNow:-(365 * 20 * 24 * 3600)];
    //获取当前的值
    NSDateFormatter *matter=[[NSDateFormatter alloc] init];
    NSString *time=self.endTimeField.text;
    matter.dateFormat=@"yyyy年MM月dd";
    NSDate *date=[matter dateFromString:time];
    // 设置最大选择时间
    _datePicker.maximumDate = date;
    // 设置时间间隔
    _datePicker.minuteInterval = 2;
    
    // 监听时间选择器值改变时间
    // 提示：除了按钮，其它能够添加事件的控件，一般都是UIControlEventValueChanged事件
    [_datePicker addTarget:self action:@selector(dateValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    return _datePicker;
}
#pragma mark - 懒加载控件
- (UIDatePicker *)datePicker1 {
    DLog(@"创建了日期选择器");
    // 创建日期选择器
    // 一般不需要设置宽高
    _datePicker1 = [[UIDatePicker alloc] init];
    // 设置时区
    _datePicker1.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    // 设置时间模式
    _datePicker1.datePickerMode = UIDatePickerModeDate;
    NSDateFormatter *matter=[[NSDateFormatter alloc] init];
    NSString *time=self.startTimeField.text;
    matter.dateFormat=@"yyyy-MM-dd";
    NSDate *date=[matter dateFromString:time];
    // 设置最小选择时间
    _datePicker1.minimumDate =date;
    // 设置最大选择时间
    _datePicker1.maximumDate = [NSDate date];
    // 设置时间间隔
    _datePicker1.minuteInterval = 2;
    
    // 监听时间选择器值改变时间
    // 提示：除了按钮，其它能够添加事件的控件，一般都是UIControlEventValueChanged事件
    [_datePicker1 addTarget:self action:@selector(dateValueChanged:) forControlEvents:UIControlEventValueChanged];
    return _datePicker1;
}

/**
 *  监听日期改变事件
 */
- (void)dateValueChanged:(UIDatePicker *)datePicker {
    // 获得当前显示的时间
    NSDate *date = datePicker == nil? [NSDate date]: datePicker.date;
    // 创建日期格式化对象
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 设置时间格式
    fmt.dateFormat  =@"yyyy-MM-dd";
    // 将日期转换成字符串
    NSString *timeStr =[fmt stringFromDate:date];
    if (self.tagNum==200) {
        self.startTimeField.text=timeStr;
    }else if (self.tagNum==201)
    {
        self.endTimeField.text=timeStr;
    }
    
}




@end
